package com.self.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.self.reggie.common.CustomException;
import com.self.reggie.dto.SetmealDto;
import com.self.reggie.entity.Setmeal;
import com.self.reggie.entity.SetmealDish;
import com.self.reggie.mapper.SetmealMapper;
import com.self.reggie.service.SetmealDishService;
import com.self.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息
        this.save(setmealDto);

        //保存菜品信息,套餐页面里面的关联菜品信息的属性是在SetmealDish里面的
        //其中setmealDto已经包含了套餐和菜品的所有信息,唯独菜品里面少了一个套餐id,需要添上
        List<SetmealDish> setmealDishList=setmealDto.getSetmealDishes();
        setmealDishList.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishList);
    }

    @Override
    public void removeWithDish( List<Long> ids ) {
        //先删除setmeal表中的数据,首先要判断该套餐是否在售,在售就不能删除
            //先查询
            LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper();
            queryWrapper.in(Setmeal::getId,ids);
            queryWrapper.eq(Setmeal::getStatus,1);

            if (this.count(queryWrapper)>0){
                //如果有套餐正处于在售状态
                throw new CustomException("套餐正在售卖,不能删除");
            }

            this.removeByIds(ids);

        //删除SetmealDish表中的数据
        LambdaQueryWrapper<SetmealDish> queryWrapper1=new LambdaQueryWrapper();
        queryWrapper1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper1);
    }
}
